<template>
  <div class="add-survey-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>创建调查问卷</h1>
      <p>设置问卷基础信息并开始设计您的调查问卷</p>
    </div>

    <!-- 分类管理区域 -->
    <a-card class="category-card" title="问卷分类管理">
      <div class="category-header">
        <a-button 
          type="primary" 
          icon="plus" 
          @click="showCategoryModal = true"
        >
          添加分类
        </a-button>
      </div>
      
      <!-- 分类列表 -->
      <a-list 
        v-if="categories.length > 0"
        item-layout="horizontal"
        data-source="categories"
        class="category-list"
      >
        <template #renderItem="category">
          <a-list-item>
            <a-list-item-meta 
              title="category.name"
              description="问卷数量: 0"
            />
            <a-button 
              size="small" 
              type="text" 
              icon="edit"
              @click="handleEditCategory(category)"
            >
              编辑
            </a-button>
          </a-list-item>
        </template>
      </a-list>
      
      <!-- 空状态 -->
      <a-empty 
        v-else
        description="暂无分类，请添加分类后创建问卷"
      />
    </a-card>

    <!-- 创建问卷按钮 -->
    <div class="create-btn-container">
      <a-button 
        type="primary" 
        size="large" 
        icon="form"
        @click="showBasicInfoModal = true"
        :disabled="categories.length === 0"
      >
        新建调查问卷
      </a-button>
      <a-tooltip v-if="categories.length === 0">
        <template #title>请先添加分类</template>
        <span class="create-btn-hint">请先添加分类才能创建问卷</span>
      </a-tooltip>
    </div>

    <!-- 添加/编辑分类弹窗 -->
    <a-modal
      v-model:visible="showCategoryModal"
      :title="categoryModalTitle"
      @ok="handleCategoryConfirm"
      @cancel="handleCategoryCancel"
    >
      <a-form-model
        :model="categoryForm"
        :rules="categoryRules"
        ref="categoryFormRef"
      >
        <a-form-model-item
          label="分类名称"
          name="name"
        >
          <a-input
            v-model="categoryForm.name"
            placeholder="请输入分类名称"
            maxlength="50"
          />
        </a-form-model-item>
      </a-form-model>
    </a-modal>

    <!-- 问卷基础信息弹窗 -->
    <a-modal
      v-model:visible="showBasicInfoModal"
      title="问卷基础信息设置"
      :footer="null"
      width="600px"
    >
      <a-form-model
        :model="surveyForm"
        :rules="surveyRules"
        ref="surveyFormRef"
        layout="vertical"
      >
        <a-form-model-item
          label="问卷标题"
          name="title"
          :label-col="{ span: 24 }"
          :wrapper-col="{ span: 24 }"
        >
          <a-input
            v-model="surveyForm.title"
            placeholder="请输入问卷标题"
            maxlength="100"
          />
          <div class="form-hint">最多100个字符</div>
        </a-form-model-item>

        <a-form-model-item
          label="所属分类"
          name="categoryId"
          :label-col="{ span: 24 }"
          :wrapper-col="{ span: 24 }"
        >
          <a-select
            v-model="surveyForm.categoryId"
            placeholder="请选择分类"
          >
            <a-select-option
              v-for="category in categories"
              :key="category.id"
              :value="category.id"
            >
              {{ category.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>

        <a-form-model-item
          label="问卷描述"
          name="description"
          :label-col="{ span: 24 }"
          :wrapper-col="{ span: 24 }"
        >
          <a-textarea
            v-model="surveyForm.description"
            placeholder="请输入问卷描述（可选）"
            rows="4"
            maxlength="500"
          />
          <div class="form-hint">最多500个字符</div>
        </a-form-model-item>

        <a-form-model-item
          :label-col="{ span: 24 }"
          :wrapper-col="{ span: 24 }"
        >
          <a-checkbox v-model="surveyForm.isAnonymous">
            允许匿名提交
          </a-checkbox>
          <div class="form-hint">开启后，将不记录提交者的个人信息</div>
        </a-form-model-item>
      </a-form-model>

      <div class="modal-actions">
        <a-button @click="showBasicInfoModal = false">取消</a-button>
        <a-button 
          type="primary" 
          @click="handleSaveAndNext"
        >
          下一步：设计表单
        </a-button>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'

// 获取组件实例和路由
const { proxy } = getCurrentInstance()
const router = useRouter()

// 分类相关状态
const categories = ref([
  { id: 1, name: '心理健康测评' },
  { id: 2, name: '性格测试' },
  { id: 3, name: '情绪评估' }
])
const showCategoryModal = ref(false)
const categoryModalTitle = ref('添加分类')
const currentEditCategory = ref(null)
const categoryFormRef = ref(null)

// 分类表单数据
const categoryForm = reactive({
  name: ''
})

// 分类表单验证规则
const categoryRules = reactive({
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { max: 50, message: '分类名称不能超过50个字符', trigger: 'blur' }
  ]
})

// 问卷基础信息相关状态
const showBasicInfoModal = ref(false)
const surveyFormRef = ref(null)

// 问卷表单数据
const surveyForm = reactive({
  title: '',
  categoryId: '',
  description: '',
  isAnonymous: false
})

// 问卷表单验证规则
const surveyRules = reactive({
  title: [
    { required: true, message: '请输入问卷标题', trigger: 'blur' },
    { max: 100, message: '问卷标题不能超过100个字符', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择所属分类', trigger: 'change' }
  ]
})

// 初始化
onMounted(() => {
  // 实际项目中可以从API加载分类数据
  // loadCategories()
})

// 处理添加/编辑分类
const handleCategoryConfirm = async () => {
  // 表单验证
  await categoryFormRef.value.validate()
  
  if (currentEditCategory.value) {
    // 编辑分类
    const index = categories.value.findIndex(
      item => item.id === currentEditCategory.value.id
    )
    categories.value[index].name = categoryForm.name
    message.success('分类更新成功')
  } else {
    // 添加新分类
    const newId = categories.value.length > 0
      ? Math.max(...categories.value.map(item => item.id)) + 1
      : 1
    categories.value.push({
      id: newId,
      name: categoryForm.name
    })
    message.success('分类添加成功')
  }
  
  // 重置表单和弹窗状态
  resetCategoryForm()
}

// 取消分类操作
const handleCategoryCancel = () => {
  resetCategoryForm()
}

// 重置分类表单
const resetCategoryForm = () => {
  categoryFormRef.value.resetFields()
  showCategoryModal.value = false
  currentEditCategory.value = null
  categoryModalTitle.value = '添加分类'
}

// 编辑分类
const handleEditCategory = (category) => {
  currentEditCategory.value = category
  categoryForm.name = category.name
  categoryModalTitle.value = '编辑分类'
  showCategoryModal.value = true
}

// 保存基础信息并跳转
const handleSaveAndNext = async () => {
  // 表单验证
  await surveyFormRef.value.validate()
  
  // 构造问卷基础信息
  const surveyData = {
    title: surveyForm.title,
    categoryId: surveyForm.categoryId,
    categoryName: categories.value.find(c => c.id === surveyForm.categoryId)?.name,
    description: surveyForm.description,
    isAnonymous: surveyForm.isAnonymous,
    id: Date.now() // 临时ID，实际项目由后端生成
  }
  
  // 保存到本地存储或状态管理
  localStorage.setItem('currentSurvey', JSON.stringify(surveyData))
  
  // 跳转到拖拽表单设计页面
  router.push({
    path: '/form-designer',
    query: { surveyId: surveyData.id }
  })
  
  // 关闭弹窗
  showBasicInfoModal.value = false
}
</script>

<style scoped>
.add-survey-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 24px;
}

.page-header {
  margin-bottom: 32px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 500;
}

.page-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.category-card {
  margin-bottom: 32px;
}

.category-header {
  margin-bottom: 16px;
  text-align: right;
}

.category-list {
  border-top: 1px solid #f0f0f0;
  padding-top: 16px;
}

.create-btn-container {
  text-align: center;
  margin: 40px 0;
}

.create-btn-hint {
  display: inline-block;
  margin-top: 8px;
  color: #999;
  font-size: 12px;
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  margin-top: 24px;
}

.form-hint {
  margin-top: 8px;
  color: #999;
  font-size: 12px;
}
</style>
